// pages/punchCardCircle/punchCardCircle.js
import Time from "../../utils/time"
const Player = require("../../utils/player"),

  audioList = [];
const app = getApp();
const api = require('../../utils/interface.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //    效果控制
    control: {
      audio: {
        player: {},
        id: "",
        isPlayer: true,
        isPause: false,
        startDate: '00:00',
        progress: "",
        activeProgress: {},
        aniProgress: {},
        loadSucc: false
      },
      player:"",
      movie: {}
    },
    userInfo: {
      name: "苦涩"
    },
    group_info: {},
    pkid: 1,
    detailList: [],
    page: 1,
    size: 10,
  },
  get_group_info: function() {
    var that = this;
    app.Post(api.wxapp.clock_group_info, {
      groupId: that.data.pkid,
      hasPerson: true
    }, function(res) {
      console.log(res);
      if (res.code == 1) {
        that.setData({
          group_info: res.data
        });
      }
    });
  },
  //请求圈子日记列表
  get_detail_list: function() {
    var that = this,
        player = that.data.player;
    app.Post(api.wxapp.clock_detail_list, {
      groupId: that.data.pkid,
      page: that.data.page,
      size: that.data.size
    }, function(res) {
      if (res.code == 1) {
        that.setData({
          detailList: that.data.detailList.concat(res.data.ClockDetailList)
        });

        that.initAudio();
        that.AudioProgress();
        if (res.data.ClockDetailList.length < that.data.size) {
          that.setData({
            isload_d: true
          });
        } else {
          that.setData({
            page: that.data.page + 1
          });
        }
      }
    });
  },
  imgYu: function (event) {
    var src = event.currentTarget.dataset.src;//获取data-src
    var imgList = event.currentTarget.dataset.list;//获取data-list
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
    this.setData({
      isShuaXing: false
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options);
    this.setData({
      pkid: options.id
    });
  },
  onShow: function() {
    this.get_group_info();
    this.get_detail_list();
  },
  // 初始化录音
  initAudio: function() {
    const that = this,
        control = this.data.control,
        player = new Player(),
        detailList = that.data.detailList;
    console.log(detailList)
    player.list.clear()
    let audioData = []
    console.log(detailList)
    console.log(player.list)
    for (let i = 0; i < detailList.length; i++) {
      if (detailList[i].ContentRadio != "") {
        audioList.push({
          id: "aa",
          dataUrl: detailList[i].ContentRadio,
          title: i,
          index: i,
        })
      }
    }
    console.log(audioList)
    player.list.create(audioList)
    control.audio.player = player
    that.setData({
      control: control
    })
    player.event.on("play ", function(data) {
      console.log("ahh")
    })
  },
  //    录音播放实例
  createAudioPlay: function(e) {
    const that = this,
        control = that.data.control,
        time = new Time(),
        detailList = that.data.detailList,
        isPlayer = control.audio.isPlayer,
        isPause = control.audio.isPlayer,
        url = e.currentTarget.dataset.bind,
        audio = detailList[url].ContentRadio,
        player = control.audio.player;
    control.audio.id = url
    console.log(url)
    console.log(audioList)
    let index;
    for (let j = 0; j < audioList.length; j++) {
      if (audioList[j].index == url) {
        index = audioList[j]._id
      }
    }

    //      判断是否点击当前录音
    if (player.list.current() !== null && player.list.current().index != url) {
      //        点击别的录音
      that.audioProgressAnimation(0, control.audio.progress, "00:00")
      player.stop()
      if (!player.isPlaying()) {
        console.log("开始播放")
        player.invoke(index)
        control.audio.isPlayer = false
        that.setData({
          control: control
        })
      }
      player.event.on('timeupdate', function(data) {
        console.log("开始监听")
        if (data.status == 1) {
          let startDate = time.secondConvertMinute(data.currentPosition)
          let actWidth = parseFloat(data.currentPosition / data.duration)
          if ((data.duration - data.currentPosition) == 0) {
            console.log("audio end")
            player.stop()
            control.audio.isPlayer = true
          } else {
            that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
          }
        }
      })
    } else {
      player.event.on('timeupdate', function(data) {
        console.log("开始监听")
        if (data.status == 1) {
          console.log(data)
          let startDate = time.secondConvertMinute(data.currentPosition)
          let actWidth = parseFloat(data.currentPosition / data.duration)
          console.log(actWidth)
          that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
          if ((data.duration - data.currentPosition) == 0) {
            console.log("audio end")
            player.stop()
            control.audio.isPlayer = true
          } else {
            //that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
          }
        }
      })
      //点击当当前的录音
      console.log("ahhh")
      // 是否播放
      if (isPlayer) {
        console.log("创建播放")
        if (player.isPaused()) {
          console.log("继续播放")
          player.resume()
        } else {
          if (!player.isPlaying()) {
            console.log("开始播放")
            player.invoke(index)
          }
        }
        control.audio.isPlayer = !isPlayer
        that.setData({
          control: control
        })
      } else {
        if (!player.isPaused()) {
          player.pause()
        }
        control.audio.isPlayer = !isPlayer
        that.setData({
          control: control
        })
      }
    }
  },
  //    录音播放进度条
  AudioProgress: function() {
    const that = this,
        control = that.data.control;
    let systemInfo = {}
    wx.getSystemInfo({
      success: res => {
        systemInfo = res
      }
    })
    control.audio.progress = systemInfo.screenWidth * 0.3
    this.setData({
      control: control,
      systemInfo:systemInfo
    })
  },
  //    录音播放进度条动画
  audioProgressAnimation: function(activeProgress, progresWidth, startDate) {
    const that = this,
        control = that.data.control,
        activePro = wx.createAnimation({}),
        aniPro = wx.createAnimation({});
    //  根据歌曲播放百分比 获取active长度
    const width = progresWidth * activeProgress
    let actWidth = parseFloat(progresWidth - width)
    console.log(activeProgress)
    console.log(width)
    console.log(progresWidth)
    activePro.width(width*2).step()
    console.log(actWidth)
    aniPro.width(actWidth).step()

    control.audio.activeProgress = activePro.export()
    control.audio.aniProgress = aniPro.export()
    control.audio.startDate = startDate
    console.log(control.audio.aniProgress)
    that.setData({
      control: control
    });
  },

  discuss: function() {
    wx.navigateTo({
      url: '../discuss/discuss'
    })
  },

  //点击关注
  touchguanZhu: function(e) {
    console.log(e);
    let that = this,
      bind = e.currentTarget.dataset.bind,
      isthumbe = e.currentTarget.dataset.isthumbe,
      accountid = e.currentTarget.dataset.accountid;
    var detailList = [];
    wx.showLoading()
    //添加关注
    if (!isthumbe) {
      app.Post(api.wxapp.follow_add, {
        accountId: accountid
      }, function(res) {
        wx.hideLoading();
        if (res.code == 1) {
          for (var i = 0; i < that.data.detailList.length; i++) {
            if (accountid == that.data.detailList[i].AccountId) {
              that.data.detailList[i].IsFollowd = true;
            }
            detailList.push(that.data.detailList[i]);
          }
          that.setData({
            detailList: detailList
          });
          app.ShowMsg("关注成功");
        } else {
          app.WxAlert(res.msg);
        }
      });
    } else {
      //取消关注
      app.Post(api.wxapp.follow_delete, {
        accountId: accountid
      }, function(res) {
        wx.hideLoading();
        if (res.code == 1) {
          for (var i = 0; i < that.data.detailList.length; i++) {
            if (accountid == that.data.detailList[i].AccountId) {
              that.data.detailList[i].IsFollowd = false;
            }
            detailList: detailList
                .push(that.data.detailList[i]);
          }
          that.setData({
            detailList: detailList
          });

          app.ShowMsg("取消成功");
        } else {
          app.WxAlert(res.msg);
        }
      });
    }
  },

  // 点赞
  bindpraise: function (e) {
    let that = this,
      log = that.data.detailList,
      bind = e.currentTarget.dataset.bind,
      isHeart = log[bind].IsThumbUp,
      userINfo = that.data.userInfo;
    var param = {
      detailId: e.currentTarget.dataset.id,
      type: isHeart ? 2 : 1
    };
    app.Post(api.wxapp.clock_detail_thumb, param, function (res) {
      if (res.code == 1) {
        if (!isHeart) {
          log[bind].ThumbsUpList.push({
            AccountId: app.globalData.userInfo.Id,
            Nickname: app.globalData.userInfo.Nickname
          });
          console.log(e.currentTarget.dataset.bind)
          log[bind].IsThumbUp = true
          log[bind].ThumbsUpCount = log[bind].ThumbsUpCount + 1;
        } else {
          var thums = [];
          log[bind].IsThumbUp = false
          log[bind].ThumbsUpCount = log[bind].ThumbsUpCount - 1;
          for (var i = 0; i < log[bind].ThumbsUpList.length; i++) {
            if (log[bind].ThumbsUpList[i].AccountId != app.globalData.userInfo.Id) {
              thums.push(log[bind].ThumbsUpList[i]);
            }
          }
          log[bind].ThumbsUpList = thums;
        }
        that.setData({
          detailList: log
        });
      }
    })
  },
  // 跳转到评论页面
  discuss: function(e) {
    console.log(e);
    wx.navigateTo({
      url: '../discuss/discuss?id=' + e.currentTarget.dataset.id + "&accid=" + e.currentTarget.dataset.accid
    });
  },
  // 跳转到我的个人页面
  grzy: function (e) {
    wx.navigateTo({
      url: '../grzy/grzy?id=' + e.currentTarget.dataset.accid
    })
  },
})